from gameset.phoenicia.base import *


class AnimalGood(Good):
    pass


class Meat(Food, AnimalGood):
    singular  =_ ('Meat')
    plural    =_ ('Meat')
    happiness =_ (1.0)
    consumed  =_ (1.5)


class AnimalRange(Building):
    size        =_ (6)
    cost        =_ (300)
    animal      =_ (None)
    herd_size   =_ (8)
    is_passable =_ (True)
    
    herd = ListAttribute()

    def construction(self):
        for _ in range(self.herd_size):
            self.give_birth()
    
    def give_birth(self, position = None):
        self._herd.append(self.spawn(self.animal, position))
    
    def day(self, day, month, year):
        self._herd = [animal for animal in self.herd if animal.exists]
    
    @property
    def is_overcrowded(self):
        return len(self._herd) > self.herd_size
    
    @property
    def spawn_point(self):
        return self.area.random_position


class RanchAnimal(Seeker):
    speed    =_ (5)
    produces =_ (None)
    meat     =_ (None)
    
    def birth(self):
        self.process(self.eat, self.calendar.per_year(self.capacity))
    
    def eat(self, num):
        if self.chance(0.5 + self.tile.terrain.fertility / 2):
            self.create(self.produces(num))
    
    def day(self, day, month, year):
        if self.one_in(100):
            self.home.give_birth(self.position)
        elif self.home.is_overcrowded and self.one_in(25):
            self.destroy()
    
    def on_idle(self):
        if self.one_in(200):
            self.move_to(self.home.area.random_position)


class Rancher(Seeker):
    color    =_ (Brown + White)
    capacity =_ (50)
    radius   =_ (15)
    
    def day(self, day, month, year):
        for animal in self.tile.nearby(RanchAnimal, radius = 1):
            if animal.home.is_overcrowded and self.storage.is_empty:
                self.slaughter(animal)
                self.move_home()
                
                return
            else:
                self.load_from(animal)
        
        if self.storage.is_full or self.one_in(250):
            self.move_home()
    
    def on_idle(self):
        if self.one_in(100):
            self.move_to_animal()
    
    def move_to_animal(self):
        self.move_to_random(self.tile.nearby(RanchAnimal, self.radius))
    
    def slaughter(self, animal):
        animal.destroy()
        self.create(Meat(animal.meat))
    
    def on_arrival_home(self):
        if self.storage.is_empty:
            self.destroy()
        else:
            self.unload_into(self.home)


class Ranch(StaffedBuilding):
    name       =_ ('Ranch')
    size       =_ (3)
    cost       =_ (800)
    staff      =_ (35)
    agents     =_ (5)
    profession =_ (Rancher)
    color      =_ (Brown.light.lighter + Black)
    stores     =_ (AnimalGood(1000))
    supply     =_ ([AnimalGood])
    
    @property
    def spawn_point(self):
        return self.access_point
